package com.quectel.core.module.parkingcard.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.parkingcard.dao.ParkingCardMemberDeviceDao;
import com.quectel.core.module.parkingcard.dto.ParkingCardMemberDeviceDto;
import com.quectel.core.module.parkingcard.entity.ParkingCardMemberDeviceEntity;
import com.quectel.core.module.parkingcard.service.ParkingCardMemberDeviceService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2023/04/24 15:24
 */
@DubboService
public class ParkingCardMemberDeviceServiceImpl extends ServiceImpl<ParkingCardMemberDeviceDao, ParkingCardMemberDeviceEntity> implements ParkingCardMemberDeviceService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ParkingCardMemberDeviceServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> PARKING_CARD_MEMBER_DEVICE_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "PARKING_CARD_MEMBER_DEVICE_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<ParkingCardMemberDeviceDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(PARKING_CARD_MEMBER_DEVICE_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private ParkingCardMemberDeviceDao parkingCardMemberDeviceDao;

    @Override
    public List<ParkingCardMemberDeviceDto> selectByMemberId(Long memberId) {
        List<ParkingCardMemberDeviceEntity> parkingCardMemberDeviceEntities = parkingCardMemberDeviceDao.selectByMemberId(memberId);
        List<ParkingCardMemberDeviceDto> parkingCardMemberDeviceDtos = CopyUtils.copyList(parkingCardMemberDeviceEntities, ParkingCardMemberDeviceDto.class);
        parkingCardMemberDeviceDtos.forEach(this::paddingField);
        return parkingCardMemberDeviceDtos;
    }

    @Override
    public void updateByUk(ParkingCardMemberDeviceDto dto) {
        ParkingCardMemberDeviceEntity entity = CopyUtils.copyObj(dto, ParkingCardMemberDeviceEntity.class);

        parkingCardMemberDeviceDao.update(entity, new LambdaQueryWrapper<ParkingCardMemberDeviceEntity>()
                .eq(ParkingCardMemberDeviceEntity::getParkingCardMemberId, dto.getParkingCardMemberId())
                .eq(ParkingCardMemberDeviceEntity::getDeviceId, dto.getDeviceId())
                .eq(ParkingCardMemberDeviceEntity::getAuthType, dto.getAuthType()));

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    @Transactional
    public void cleanAndSaveBatch(List<ParkingCardMemberDeviceDto> memeberDeviceRefDtos) {
        Map<Long, List<ParkingCardMemberDeviceDto>> memberDeviceGroupByMemberIdMap = memeberDeviceRefDtos.parallelStream()
                .collect(Collectors.groupingBy(ParkingCardMemberDeviceDto::getParkingCardMemberId));
        for (Map.Entry<Long, List<ParkingCardMemberDeviceDto>> longListEntry : memberDeviceGroupByMemberIdMap.entrySet()) {
            parkingCardMemberDeviceDao.delete(new LambdaQueryWrapper<ParkingCardMemberDeviceEntity>()
                    .eq(ParkingCardMemberDeviceEntity::getParkingCardMemberId, longListEntry.getKey()));
            List<ParkingCardMemberDeviceEntity> parkingCardMemberDeviceEntities = CopyUtils.copyList(longListEntry.getValue(), ParkingCardMemberDeviceEntity.class);
            for (ParkingCardMemberDeviceEntity parkingCardMemberDeviceEntity : parkingCardMemberDeviceEntities) {
                parkingCardMemberDeviceEntity.setId(Snowflake.nextId());
            }
            super.saveBatch(parkingCardMemberDeviceEntities);
        }
    }

    @Override
    public ParkingCardMemberDeviceDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                PARKING_CARD_MEMBER_DEVICE_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public ParkingCardMemberDeviceDto selectById(Long id) {
        ParkingCardMemberDeviceEntity entity = parkingCardMemberDeviceDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, ParkingCardMemberDeviceDto.class));
    }

    @Override
    public List<ParkingCardMemberDeviceDto> queryList(Map<String, Object> params) {
        List<ParkingCardMemberDeviceEntity> list = parkingCardMemberDeviceDao.queryList(params);
        List<ParkingCardMemberDeviceDto> result = CopyUtils.copyList(list, ParkingCardMemberDeviceDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private ParkingCardMemberDeviceDto paddingField(ParkingCardMemberDeviceDto dto) {
        if (dto != null) {

        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return parkingCardMemberDeviceDao.queryTotal(params);
    }

    @Override
    public Long save(ParkingCardMemberDeviceDto dto) {
        ParkingCardMemberDeviceEntity entity = CopyUtils.copyObj(dto, ParkingCardMemberDeviceEntity.class);
        entity.setId(Snowflake.nextId());
        parkingCardMemberDeviceDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(ParkingCardMemberDeviceDto dto) {
        ParkingCardMemberDeviceEntity entity = CopyUtils.copyObj(dto, ParkingCardMemberDeviceEntity.class);

        parkingCardMemberDeviceDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(ParkingCardMemberDeviceDto dto) {
        ParkingCardMemberDeviceEntity entity = CopyUtils.copyObj(dto, ParkingCardMemberDeviceEntity.class);

        MyBatisPlusUtils.updateAllColumnById(entity, parkingCardMemberDeviceDao);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id) {

        CLEAR_CACHE_FUNC.accept(selectById(id));

        parkingCardMemberDeviceDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
